# -*- encoding:utf-8 -*-

import time
import simplejson

from taobao.ApiConstants import *
from taobao.util.WebUtil import doGet
from taobao.util.EncryptUtil import sign
from taobao.TaobaoApiException import TaobaoApiException

class TaobaoRestClient():
    """基于REST的TOP客户端。"""

    def __init__(self, serverUrl, appKey, appSecret, format='json'):
        self.serverUrl  = serverUrl
        self.appKey     = appKey
        self.appSecret  = appSecret

        # the format is only 'xml' or 'json'
        if format not in ['xml','json']:
            format = 'json'
        self.format     = format

    def execute(self, request, parser, session=None):
        
        # get application level params
        textParams = request.getTextParams().copy()

        # set system level params
        textParams[METHOD]      = request.getApiName()
        textParams[VERSION]     = DEFAULT_SERVICE_VERSION
        textParams[APIKEY]     = self.appKey
        textParams[FORMAT]      = self.format
        textParams[TIMESTAMP]   = time.strftime('%Y-%m-%d %X', time.localtime()) 
        # 添加数字签名
        textParams[SIGN]        = sign(textParams, self.appSecret)
        if session:
            textParams[self.SESSION] = session

        # try to GET/POST rest request
        try:
            rsp = doGet(self.serverUrl, textParams)
        except :
            raise TaobaoApiException()

        self.tryParseException(rsp)
        return parser.parser(rsp)

    def tryParseException(self, rsp):
        """尝试把错误响应转化为异常。 错误格式：
        {"error_rsp":{"code":[error code],"msg":"[error message]"}} 
        """
        
        if self.format in ['json']:
            if rsp.startswith("{\"%s\":" %ERROR_RSP):
                errDict = simplejson.loads(rsp)
                errCode = errDict[ERROR_RSP][ERROR_CODE]
                errMsg  = errDict[ERROR_RSP][ERROR_MSG]
                raise TaobaoApiException(code=int(errCode), msg=errMsg)
        else:
            raise TaobaoApiException(msg="Unsupported response format:json")
 
